package network.course6.bytebuf.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import network.course6.bytebuf.handler.ServerObjectHandler;
import network.course6.bytebuf.tools.MsgDecoder;
import network.course6.bytebuf.tools.MsgEncoder;

public class ObjectServer {
    /**
     * 创建bootstrap
     */
    private static final ServerBootstrap serverBootstrap = new ServerBootstrap();
    /**
     * Worker
     */
    private static final EventLoopGroup work = new NioEventLoopGroup();
    /**
     * 端口号
     */
    private int port = getPort();

    /**
     *
     * 关闭服务器
     */
    public void close(){
        System.out.println("关闭服务器。。。");
        work.shutdownGracefully();
    }

    /**
     *
     * 开启服务器线程
     */
    public void start(){
        serverBootstrap.group(work).channel(NioSctpServerChannel.class).option(ChannelOption.SO_BACKLOG,100).handler(new LoggingHandler(LogLevel.INFO));
        try{
            //设置事件处理
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception{
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new MsgEncoder());
                    pipeline.addLast(new MsgDecoder());
                    pipeline.addLast(new ServerObjectHandler());
                }
            });
            System.out.println("netty服务器在【"+port+"】端口启动监听");
            ChannelFuture  f = serverBootstrap.bind(port);
            f.channel().closeFuture();
        }catch (Exception e){
            System.out.println("出现异常，释放资源");
        }finally {
            close();
        }
    }

    private int getPort() {
        Double port = (Math.random() + 1) * 10000;
        return port.intValue();
    }

    public static void main(String[] args) {
        new ObjectServer().start();
    }
}
